const { useState, useEffect, useRef } = React;

// Toast notification function
function showToast(message, duration = 5000) {
    // Remove any existing toast
    const existingToast = document.querySelector('.toast-notification');
    if (existingToast) {
        existingToast.remove();
    }

    // Create toast element
    const toast = document.createElement('div');
    toast.classList.add('toast-notification');
    toast.textContent = message;

    // Add to body
    document.body.appendChild(toast);

    // Trigger show animation
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // Remove toast after duration
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, duration);
}

function App() {
    const [password, setPassword] = useState('');
    const [params, setParams] = useState({
        userId: '',
        photoId: ''
    });
    const [mediaContent, setMediaContent] = useState(null);
    const [showForm, setShowForm] = useState(true);
    const [showImage, setShowImage] = useState(false);
    const videoRef = useRef(null);

    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const userId = urlParams.get('u');
        const photoId = urlParams.get('p');
        setParams({
            userId: userId || '',
            photoId: photoId || ''
        });

        if (userId) {
            const savedPassword = localStorage.getItem(`user_${userId}_password`);
            if (savedPassword) {
                params.userId = userId;
                params.photoId = photoId;
                setPassword(savedPassword);
                handleSubmit(savedPassword);
            }
        }
    }, []);

    const handleVideoEnded = () => {
        setShowImage(true);
    };

    const handlePlayClick = () => {
        setShowImage(false);
        if (videoRef.current) {
            videoRef.current.currentTime = 0;
            videoRef.current.play();
        }
    };

    const handleSubmit = async (savedPassword = null) => {
        const currentPassword = savedPassword || password;
        
        if (!params.userId || !params.photoId) {
            alert('缺少必要参数：userId 或 photoId');
            return;
        }
        
        try {
            const requestBody = {
                userId: params.userId,
                photoId: params.photoId,
                password: currentPassword
            };

            const response = await fetch(`${CONFIG.API_BASE_URL}${CONFIG.API_ENDPOINTS.GET_PHOTO}`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(requestBody)
            });
            
            const data = await response.json();
         
            if (data.code === 200 && data.data.photo) {
                localStorage.setItem(`user_${params.userId}_password`, currentPassword);
                
                const photo = data.data.photo;
                setShowForm(false);

                if (photo.nfcQrcode === "无") {
                    setMediaContent({
                        type: 'image',
                        url: photo.imageUrl
                    });
                } else {
                    if (photo.videoUrl) {
                        setMediaContent({
                            type: 'video',
                            url: photo.videoUrl,
                            imageUrl: photo.imageUrl
                        });
                        setShowImage(false);
                    } else {
                        setMediaContent({
                            type: 'image',
                            url: photo.imageUrl
                        });
                        showToast('请去小程序上传视频');
                    }
                }
            } else {
                localStorage.removeItem(`user_${params.userId}_password`);
                    alert(data.message || '获取照片失败');
            }
        } catch (error) {
            console.error('API Error:', error);
            alert('请求失败，请检查网络连接');
        }
    };

    if (!showForm && mediaContent) {
        return (
            <div className="media-container">
                {mediaContent.type === 'video' ? (
                    showImage ? (
                        <div className="image-with-play">
                            <img 
                                src={mediaContent.imageUrl} 
                                alt="视频封面"
                                style={{
                                    width: '100%',
                                    height: '100%',
                                    objectFit: 'contain'
                                }}
                            />
                            <div className="play-button" onClick={handlePlayClick}></div>
                        </div>
                    ) : (
                        <video 
                            ref={videoRef}
                            src={mediaContent.url}
                            poster={mediaContent.imageUrl}
                            controls
                            autoPlay
                            playsInline
                            onEnded={handleVideoEnded}
                            style={{
                                width: '100%',
                                height: '100%',
                                objectFit: 'contain'
                            }}
                        />
                    )
                ) : (
                    <img 
                        src={mediaContent.url}
                        alt="照片"
                        style={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'contain'
                        }}
                    />
                )}
            </div>
        );
    }

    return (
        <div className="login-container">
            <div className="form-group">
                <input
                    type="password"
                    className="password-input"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="请输入密码"
                />
                <button 
                    className="submit-button"
                    onClick={() => handleSubmit()}
                >
                    确认
                </button>
            </div>
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
